package cn.hy.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class JobDemo {

    //注入任务对象工厂
   @Resource
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定,注入step对象的factory
   @Resource
    private StepBuilderFactory stepBuilderFactory;

    //创建Job对象
    @Bean
    public Job jobDemo1() {
        return jobBuilderFactory.get("jobDemo1")
                // 多个步骤
                .start(step1()).next(step2()).next(step3())
                .build();
    }

    //创建Step对象
    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                log.info("------step1 ok");
                return RepeatStatus.FINISHED;
            }
        }).build();
    }

    //创建Step对象
    @Bean
    public Step step2() {
        return stepBuilderFactory.get("step2").tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                log.info("------step2 ok");
                return RepeatStatus.FINISHED;
            }
        }).build();
    }

    //创建Step对象
    @Bean
    public Step step3() {
        return stepBuilderFactory.get("step3").tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                log.info("------step3 ok");
                return RepeatStatus.FINISHED;
            }
        }).build();
    }


    // Flow是一组Step的集合，一个Job可以包含多个Flow，一个Flow可以包含多个Step，同时一个Job也可以同时包含Flow和Step。

   // 创建Flow对象，声明flow中包含哪些step
    @Bean
    public Flow flow1(){
        return new FlowBuilder<Flow>("flow1").start(step1()).next(step2()).build();
    }

    @Bean
    public Job job01(){
        return jobBuilderFactory.get("job1").start(flow1()).next(step3()).end().build();
    }
}
